﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using X.Web;
using System.IO;

namespace X.WebSite.Admin.Ad
{
    public partial class Detail : AdminPage
    {
        int _Id
        {
            get
            {
                int id = 0;

                if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
                    id = int.Parse(Request.QueryString["Id"]);

                return id;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                X.Entity.AdInfo adInfo = Bll.Ad.GetAdInfo(_Id);

                txtAdName.Text = X.Common.StringUtils.HtmlDecode(adInfo.AdName);
                txtAdLink.Text = adInfo.AdLink;
                txtOrderNum.Text = adInfo.OrderNum.ToString();

                imgAd.ImageUrl = string.Format("/Upload/{0}", adInfo.AdImage);
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            X.Entity.AdInfo adInfo;
            
            if (0 != _Id)
            { 
                adInfo = Bll.Ad.GetAdInfo(_Id);

                adInfo.AdName = X.Common.StringUtils.HtmlEncode(txtAdName.Text);
                adInfo.AdLink = txtAdLink.Text;
                adInfo.OrderNum = int.Parse(txtOrderNum.Text);
                adInfo.IsShow = chkIsShow.Checked;

                adInfo.AdImage = UploadImage(adInfo.AdImage);

                Bll.Ad.Update(adInfo);
            }
            else
            { 
                adInfo = new Entity.AdInfo();

                adInfo.AdName = X.Common.StringUtils.HtmlEncode(txtAdName.Text);
                adInfo.AdLink = txtAdLink.Text;
                adInfo.OrderNum = int.Parse(txtOrderNum.Text);
                adInfo.IsShow = chkIsShow.Checked;

                adInfo.AdImage = UploadImage(string.Empty);

                Bll.Ad.Create(adInfo);
            }

            Response.Redirect("List.aspx");
        }

        string UploadImage(string imgName)
        {
            if (null == this.FileUpload1.PostedFile || this.FileUpload1.PostedFile.ContentLength == 0)
                return imgName;

            string ext = Path.GetExtension(this.FileUpload1.PostedFile.FileName);
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string savePath = Server.MapPath("/Upload/");

            this.FileUpload1.PostedFile.SaveAs(savePath + fileName + ext);

            return savePath + fileName + ext;
        }
    }
}